﻿using System;
using System.Collections;
using ProjectDanmaku.Broadcast;
using UnityEngine;
using Random = System.Random;

namespace ProjectDanmaku.Effect
{
    public class CameraShakeEffect : MonoBehaviour
    {
        private Random _random = new Random();
        
        private bool _inAnimation = false;

        [SerializeField] private AnimationCurve attenuationCurve;
        
        private void OnEnable()
        {
            BroadcastServer.Instance.ListenChannel(CommonChannel.CameraShakeChannel, BeginShake);
        }

        private void OnDisable()
        {
            BroadcastServer.Instance.StopListeningAllChannelsForObject(this);
        }

        public void BeginShake(BroadcastReceiverInfo _)
        {
            if (_inAnimation)
                return;

            StartCoroutine(CameraShakeCoroutine());
        }
        
        private IEnumerator CameraShakeCoroutine()
        {
            var pos = transform.position;

            var t = 0f;

            while (t <= 1)
            {
                var atten = attenuationCurve.Evaluate(t);
                var randomMotionVector = new Vector2(
                    _random.Next(-100, 100), _random.Next(-100, 100)).normalized * atten;
                
                transform.position = pos + new Vector3(randomMotionVector.x, randomMotionVector.y, 0);
                
                t += 0.05f;

                yield return new WaitForSeconds(0.05f);
            }

            transform.position = pos;
        }
    }
}